<template>
    <el-dialog v-model="DialogShow" width="30%" title="导入作业" center custom-class="custom_class ">
        <div class="main">
            <el-form :model="form" ref="ruleFormRef" label-width="auto" style="max-width: 600px" :rules="ruleForm">
                <el-form-item label="作业名称" prop="workName">
                    <el-input v-model="form.workName" placeholder="请输入作业名称" />
                </el-form-item>
                <el-form-item label="截至时间" prop="deadlineTime">
                    <el-date-picker v-model="form.deadlineTime" type="date" placeholder="请选择" clearable />
                </el-form-item>
                <el-form-item label="上传作业文件" prop="fileList">
                    <el-upload ref="upload" class="upload-demo" accept=".pdf,.docx" v-model:file-list="form.fileList"
                        action="http://123.249.111.34:3000/uploadFile" :limit="1" :on-exceed="handleExceed"
                        :auto-upload="true" multiple :on-preview="handlePreview" :on-remove="handleRemove"
                        :before-upload="beforeUpload" :on-success="handleSuccess">
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                        <template #tip>
                            <div class="el-upload__tip text-red">
                                只能选择一个文件
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="DialogShow = false">取消</el-button>
                <el-button type="primary" @click="submitForm"> 确定 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';

import useUserInfo from "store/useUserInfo.js";
const useUserInfoStore = useUserInfo();
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserInfoStore)

import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps(['show', 'courseId'])
const emit = defineEmits(['update:show', 'onSubmit'])

import { addHomeworkApi } from "@/api/index";


const upload = ref(null)
const DialogShow = ref(false)
watch(() => props.show, (newVal) => {
    console.log(newVal, 'newVal');
    if (!newVal) {
        form.workName = "";
        form.deadlineTime = null
        form.fileList = []
    }
    DialogShow.value = newVal;
});
watch(() => DialogShow.value, (newVal) => {
    emit('update:show', newVal);
});

// 数据收集
const form = reactive({
    workName: '',
    fileList: [],
    deadlineTime: null
})
// 删除上传文件
const handleRemove = (file, uploadFiles) => {
    form.fileList = []
}
const handlePreview = (uploadFile) => {
    console.log(form.fileList);

}
// 上传前
const beforeUpload = (file) => {
    // 在文件上传之前进行校验  
    const isPDFOrDOCX = file.type === 'application/pdf' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    if (!isPDFOrDOCX) {
        ElMessage({
            showClose: true,
            message: "只能上传pdf/docx文件",
            type: "error",
        });
        return false;
    }
    return isPDFOrDOCX;
}

const handleExceed = (files, uploadFiles) => {
    ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
    )
}


// 上传成功
const handleSuccess = () => {
    console.log(form.fileList);
}
// 表单验证
const ruleForm = reactive({
    workName: [
        { required: true, message: '请输入作业名称', trigger: 'blur' },
    ],
    deadlineTime: [
        { required: true, message: '请选择截至日期', trigger: 'blur' },
    ],
    fileList: [
        {
            type: 'array',
            required: true,
            message: '必须选择一个文件',
            trigger: 'blur',
        },
    ],
})
const ruleFormRef = ref(null);
const submitForm = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            const params = {
                deadlineTime: form.deadlineTime,
                workName: form.workName,
                operatorId: userInfo.value.userId,
                courseId: props.courseId,
                type: 1,
            }
            const workUrl = handleAvatarSuccess()
            params.workUrl = workUrl
            const res = await addHomeworkApi(params)
            if (res.code !== "10000") {
                ElMessage({
                    showClose: true,
                    message: res.message,
                    type: "error",
                });
                return;
            }
            ElMessage({
                showClose: true,
                message: `添加成功!`,
                type: "success",
            });
            emit('onSubmit')
            DialogShow.value = false;
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 处理上传的图片地址

const handleAvatarSuccess = () => {
    const file = form.fileList[0].response.data.data;
    const { Location } = file
    // 拼接地址
    return `http://${Location}`
}
</script>

<style lang="scss"></style>